const qiniu = require("qiniu");
const moment=require('moment');
const {qiniu_bucket,qiniu_domain,qiniu_zone} = require('../config/config');
const config={
    "AccessKey": "G_jFzBXSQiXnlArInNuNFMGZcS5DE1IiNpgDf-Ua", 
	"SecretKey": "J581ybep4tuaZnefiZRzgN5zXOiLxj4_tS7Ci2X_",
    "Bucket": qiniu_bucket,
    "Port": 9000,
    "UptokenUrl": "token",
};

function getAccessToken(url){
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	return qiniu.util.generateAccessToken(mac,url);
}

function getUploadToken(){
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	const time=moment().add(24,'h').startOf('h').unix();
	const options = {
	    scope: config.Bucket,
	    saveKey: '$(etag)${ext}',
		deadline:time,
	    returnBody:
	        '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(fname)","uid":"${uuid}","type":"${mimeType}"}'
	};
	const putPolicy = new qiniu.rs.PutPolicy(options);
	const upload_token = putPolicy.uploadToken(mac);
	return upload_token;
}

//指定文件名上传文件
function getUploadAssignKeyToken(key){
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	const time=moment().add(24,'h').startOf('h').unix();
	const options = {
		scope: config.Bucket+":"+key,
		saveKey: '$(etag)${ext}',
		deadline:time,
		insertOnly:0,
		returnBody:
			'{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(fname)","uid":"${uuid}","type":"${mimeType}"}'
	};
	const putPolicy = new qiniu.rs.PutPolicy(options);
	const upload_token = putPolicy.uploadToken(mac);
	return upload_token;
}

//获取压缩文件(少量mkzip/2)id
// @param saveas - 压缩包文件名
// @param urls  - 包含压缩文件url数组(已上传至七牛)
// @param callbackFunc(err, respBody, respInfo) - 回调函数
function getPfop2Id(saveas,urls,callbackFunc){
	var sUrls = "";
	//var fops = [];
	urls.forEach(url=>{
		const encoded = qiniu.util.urlsafeBase64Encode(url);
		//var encodedUrl = encoded.replace(/\//g, '_').replace(/\+/g, '-')//.replace(/=+$/g, '');
		const safeUrl = "/url/" + encoded;
		sUrls = sUrls+safeUrl;
	});
	const encodedSaveas = "|saveas/"+qiniu.util.urlsafeBase64Encode(config.Bucket+":"+saveas);
	const fops = ["mkzip/2/encoding/"+qiniu.util.urlsafeBase64Encode('gbk')+sUrls+encodedSaveas];
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	var qiniuConfig = new qiniu.conf.Config();
	config.zone = qiniu.zone.Zone_z0;
	const options = {
		// notifyURL: 'http://api.example.com/pfop/callback',
		// force: true,
	};
	const pipeline = 'zip_report';
	const om = new qiniu.fop.OperationManager(mac,qiniuConfig);
	om.pfop(config.Bucket,"1.png",fops,pipeline,null,function(err,crespBody,respInfo) {
		callbackFunc(err,crespBody,respInfo);
	});
}

//url转换及拼接
function urls2Content(urls){
	var content = "";
	for(var i=0;i<urls.length;i++){
		const url = urls[i];
		const encoded = qiniu.util.urlsafeBase64Encode(url);
		//var encodedUrl = encoded.replace(/\//g, '_').replace(/\+/g, '-')//.replace(/=+$/g, '');
		const safeUrl = "/url/" + encoded;
		if(i==0){
			content = safeUrl;
		}else{
			content = content + "\n" + safeUrl;
		}
	}
	return content;
}

//获取压缩文件(多量mkzip/4)id
// @param key  - 包含压缩文件url的索引文件(已上传至七牛)
// @param saveas - 压缩包文件名
// @param callbackFunc(err, respBody, respInfo) - 回调函数
function getPfop4Id(key,saveas,callbackFunc){
	const encodedSaveas = "|saveas/"+qiniu.util.urlsafeBase64Encode(config.Bucket+":"+saveas);
	const fops = ["mkzip/4/encoding/"+qiniu.util.urlsafeBase64Encode('gbk')+encodedSaveas];
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	var qiniuConfig = new qiniu.conf.Config();
	config.zone = qiniu.zone.Zone_z0;
	const options = {
		force: true
	};
	const pipeline = 'zip_report';
	const om = new qiniu.fop.OperationManager(mac,qiniuConfig);
	om.pfop(config.Bucket,key,fops,pipeline,options,function(err,crespBody,respInfo) {
		callbackFunc(err,crespBody,respInfo);
	});
}

function getZipResult(persistentId,callbackFunc){
	const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
	var qiniuConfig = new qiniu.conf.Config();
	var operManager = new qiniu.fop.OperationManager(mac, qiniuConfig);
	operManager.prefop(persistentId, function(err, respBody, respInfo) {
		callbackFunc(err,respBody,respInfo);
	});
}

/*
* 复制resUrl的文件到七牛，文件名为key
* 返回
* {
  url: 'http://file-jzy.jiaozuoye.online/202212011534.png',
  fsize: 22757,
  hash: 'FhmBnGvFcG6SJraxCOzuvJOUSIzM',
  key: '202212011534.png',
  mimeType: 'image/png'
}
* */
const qn_config = new qiniu.conf.Config();
qn_config.zone = qiniu.zone[`Zone_${qiniu_zone}`];
const mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
const bucketManager = new qiniu.rs.BucketManager(mac, qn_config);
function copyFileToQiniu(resUrl, key) {
	return new Promise((resolve, reject) => {
		bucketManager.fetch(resUrl, qiniu_bucket, key, function(err, respBody, respInfo) {
			if (err) {
				reject(err);
			} else {
				if (respInfo.statusCode === 200) {
					const url=qiniu_domain+respBody.key;
					resolve({url,...respBody}); //key,hash,fsize,mimeType
				} else {
					reject(respBody);
				}
			}
		});
	});
}

module.exports = {
	getAccessToken,
	getUploadToken,
	getUploadAssignKeyToken,
	getPfop2Id,
	getPfop4Id,
	urls2Content,
	getZipResult,
	copyFileToQiniu
};